#!/usr/bin/env ruby

# Author: Greg Mefford
# This script is currently configured for parsing data out of DEM geological data and creating a height map from it.
#   Currently, it is not in a generically useful form, but the substance is there if you want to dig through it
#   for some other purpose.

require 'RMagick'
include Magick

beginning = Time.now
# Constants
IntensityScale = 0.125
HeightScale = 0.0256
HeightScaleIntensity = ((128 * HeightScale) + 0.5).to_i - 1
ImageWidth = 800
ImageHeight = 800
TileRows = 3
TileCols = 4
DefaultIntensity = 0
ImageFiles =
  ["GALAP100_0009.ASC", "GALAP100_0010.ASC", "GALAP100_0011.ASC", "",
    "GALAP100_0005.ASC", "GALAP100_0006.ASC", "GALAP100_0007.ASC", "GALAP100_0008.ASC",
    "GALAP100_0001.ASC", "GALAP100_0002.ASC", "GALAP100_0003.ASC", "GALAP100_0004.ASC",
  ]


img = Magick::Image.new(ImageWidth * TileCols, ImageHeight * TileRows) {
  self.background_color = 'black' 
}
for tile_y in 0..TileRows-1
  for tile_x in 0..TileCols-1
    filename = ImageFiles[(tile_y * TileCols) + tile_x]
    next if filename == ""
    start = Time.now
    print "filename: #{filename}"
    file = File.open(filename)
    ncols =        file.gets.split[1].to_i
    nrows =        file.gets.split[1].to_i
    xllcenter =    file.gets.split[1].to_f
    yllcenter =    file.gets.split[1].to_f
    cellsize =     file.gets.split[1].to_f
    nodata_value = file.gets.split[1].to_i
    data = file.gets.split
    array = [];
    error_count = 0
    data.each do |item|
      value = item.to_i
      if value == nodata_value
        value = DefaultIntensity
      else
        puts "Range Problem in input" if value > 2048
        value = 1 + ((value.to_f / 2048.0) * 255.0).to_i
        if value > 255
          error_count += 1
          value = 255
        end
      end  
      array << value
    end
    data = array
#    puts "ncols: #{ncols}"
#    puts "nrows: #{nrows}"
#    puts "xllcenter: #{xllcenter}"
#    puts "yllcenter: #{yllcenter}"
#    puts "cellsize: #{cellsize}"
#    puts "nodata_value: #{nodata_value}"
#    puts "Data: #{data[1..10].join(", ")}..."
    img = img.import_pixels(tile_x * ImageWidth, tile_y * ImageHeight, ImageWidth, ImageHeight, "I", data)
    print " (#{Time.now - start}s with #{error_count} output range errors)\n"
  end
end

img.write("output_raw.png")